<?php
/*
Copyright (c) 2009, Francisco Facioni
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of Fr6 & Co. nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Francisco Facioni ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Francisco Facioni BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

require_once "Database.php";

//TODO: Create some nice error logging
//TODO: Check the connection persistence, there is a php.ini configuration... This should fallback to a reconnect when needed
/**
 * This is the databes object, it's using mysqli
 */
class MySQLDatabase extends Database {
	static $connections = array();
	static $defaultConnection = null;
	
	static function instance($name = null){
		//Return the default database when no name is selected
		if(is_null($name))
			return MySQLDatabase::$defaultConnection;
		
		return MySQLDatabase::$connections[$name];
	}
	
	static function register($name,$host, $user, $password, $database){
		 $connection = new MySQLDatabase($host,$user,$password,$database);
		 MySQLDatabase::$connections[$name] = $connection;
		 //If we don't have a default connection, use the first one
		 if(is_null(MySQLDatabase::$defaultConnection))
		 	MySQLDatabase::$defaultConnection = $connection;
		 	
		 return $connection;
	}
	
	protected $mysql = null;
	
	function setAsDefault(){
		MySQLDatabase::$defaultConnection = $this;
		
		return $this;
	}
	
	function connect(){
		$this->mysql = new mysqli($this->host,$this->user,$this->password, $this->database);
		
		if (mysqli_connect_error()) {
    		throw new Exception('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
		}
		
		return $this;
	}
	
	function __destruct(){
		if(!is_null($this->mysql))
			$this->mysql->close();
			
		$this->mysql = null;
		foreach(MySQLDatabase::$connections as $name => $connection){
			if($this === $connection)
				unset(MySQLDatabase::$connections[$name]);
		}
	}
	
	function lastId(){
		$lastId = $this->mysql->insert_id;
		if($lastId === 0)
			return null;
		return $lastId;
	}
	
	function escape($value){
		$this->connect();
		
		return $this->mysql->escape_string($value);	
	}
	
	function run($query){
		$this->connect();
		
		$result = $this->mysql->query($query);
		
		if($result === false)
			throw new Exception("SQL error: {$this->mysql->error}");
		
		return $result;
	}
	
	function affectedRows(){
		return $this->mysql->affected_rows;
	}
}
?>